package com.example.demo1.config;

import com.example.demo1.Service.UserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;


@Configuration
@Order(103)
public class UsersecConfig extends WebSecurityConfigurerAdapter {
    @Resource
    UserDetailsServiceImpl userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoders());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/assets/**","/favicon.ico", "/error","/image/**","/icons/**","/nav_img/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().hasAnyRole("ADMIN","USER").and()
                .formLogin()
                .loginPage("/admin/login")
                .defaultSuccessUrl("/select").and()
                .logout()
                .logoutUrl("/logout").permitAll()
                .logoutSuccessUrl("/admin/login");

    }
    @Bean
    PasswordEncoder passwordEncoders(){
        return new BCryptPasswordEncoder();
    }
}
